package ru.niir.goodfil.ui;

import ru.niir.goodfil.db.Brand;
import org.hibernate.exception.ConstraintViolationException;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import javax.faces.model.SelectItem;
import java.util.List;
import java.util.ArrayList;

public class BrandsBean extends PageBean {

    private List<Brand> brands = gf().getBrands();
    private long brandId;
    private String name;

    public void addBrand() {
        try {
            gf().saveBrand(new Brand(name));
        }
        catch (ConstraintViolationException e) {
            facesError("Возможно, наименование брэнда не уникально?");
        }

        brands = gf().getBrands();
    }


    /**
     * Удалить брэнд
     */
    public void deleteBrand() {
        gf().removeBrand(brandId);
        brands = gf().getBrands();
    }

    public void activateBrand() {
        Brand brand = gf().getBrandById(brandId);
        brand.setActive(!brand.isActive());
        gf().updateBrand(brand);

        brands = gf().getBrands();
    }

    public List<SelectItem> getBrandsAsSelectItems() {
        List<SelectItem> result = new ArrayList<SelectItem>();
        for (Brand brand : brands) {
            result.add(new SelectItem(brand.getId(), brand.getName()));
        }
        return result;
    }

    public List<Brand> getBrands()
    {
        return brands;
    }

    public void setBrands(List<Brand> brands)
    {
        this.brands = brands;
    }

    public long getBrandId()
    {
        return brandId;
    }

    public void setBrandId(long brandId)
    {
        this.brandId = brandId;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}